package net.lc7.proto;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Description: 连接zk
 * @Author: Jason.zhu
 * @Create: 2019/05/16 16:27
 */

public class ZKConnect implements Watcher {
    static org.slf4j.Logger logger = LoggerFactory.getLogger(ZKConnect.class);

    // 连接超时时间
    private static Integer timeout;

    // 连接地址
    private static String zkServerIp;


    static {
        Properties zkProperties = new Properties();
        InputStream is = ZKConnect.class.getResourceAsStream("/zk.properties");
        try {
            zkProperties.load(is);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                logger.error("关闭流失败", e);
            }
        }
        timeout = Integer.valueOf(zkProperties.getProperty("zk.timeout"));
        zkServerIp = zkProperties.getProperty("zk.zkServerIps");
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        logger.warn("触发了[" + watchedEvent.getType().name()+"]事件");
    }

    public static ZooKeeper getZooKeeper(){
        try {
            ZooKeeper zooKeeper = new ZooKeeper(zkServerIp, timeout, new ZKConnect());
            return zooKeeper;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
